package action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import service.PointService;
import service.RoadService;
import bean.Point;
import bean.Road;
import bean.RoadStatus;
import bean.Tile;
import bean.Vehicle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.JavaBeanSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class RoadAction extends ActionSupport {

	private static final long serialVersionUID = -1087386002737805054L;

	private RoadService roadService;

	private PointService pointService;
	
	@SuppressWarnings("unchecked")
	public String uploadRoads() {

		try {

			List<Road> rs = new ArrayList<Road>();

			rs = (List<Road>) ActionContext.getContext().getSession()
					.get("roads");

			this.roadService.saveOrUpdate(rs);

			ServletActionContext.getResponse().setCharacterEncoding("utf-8");

			ServletActionContext.getResponse().getWriter()
					.write(JSON.toJSONString(rs));

		} catch (Exception e) {

			e.printStackTrace();

		}

		return NONE;
	}

	public String pushAllRoads() {

		try {

			int area = Integer.parseInt(ServletActionContext.getRequest()
					.getParameter("area"));

			ServletActionContext.getResponse().setCharacterEncoding("utf-8");

			List<Road> roads = roadService.queryAllRoadsInArea(area);

			for (Road road : roads) {

				road.setPoints(null);

				for (Point p : road.getPoint()) {

					p.setRoad(null);

					p.setRoads(null);

					p.setArea(null);

				}

			}

			ServletActionContext.getResponse().getWriter()
					.write(roads.toString());

		} catch (Exception e) {

			e.printStackTrace();

		}

		return NONE;
	}

	public String deleteRoad() {
		try {
			int id = Integer.parseInt(ServletActionContext.getRequest()
					.getParameter("id"));

			roadService.removeRoadById(id);

			ServletActionContext.getResponse().getWriter().write("ok");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public String basicRoute() {
		try {
			HttpServletRequest req = ServletActionContext.getRequest();
			String str = req.getParameter("points");
			JSONArray jarray = JSON.parseArray(str);
			Point[] points = new Point[2];
			points[0] = JSON.toJavaObject(jarray.getJSONObject(0), Point.class);
			points[1] = JSON.toJavaObject(jarray.getJSONObject(1), Point.class);
			int[] ids = pointService.shortestPoint(points, points[0].getArea()
					.getId());
			List<Point> ps = new ArrayList<Point>();
			if (ids[0] != -1) {
				List<Point> se = pointService.findPointsByIds(ids);
				if (se.size() != 2) {
					ServletActionContext.getResponse().getWriter()
							.write("error");
					return NONE;
				}
				ps = roadService.shortestPath(points[0].getArea().getId(),
						se.get(0), se.get(1), ids[0] == 0);
			} else {
				ps.addAll(Arrays.asList(points));
			}
			for (Point p : ps) {
				p.setRoad(null);
				p.setArea(null);
			}
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter()
					.write(JSON.toJSONString(ps));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public String vehicleMovement() {
		try {
			HttpServletRequest req = ServletActionContext.getRequest();
			int area = Integer.parseInt(req.getParameter("area"));
			List<Vehicle> vs = roadService.getCurrentVehicleMovement(area);
			vs=roadService.circleFilter(vs, 1);
			SerializeConfig mapping = new SerializeConfig();
			mapping.put(Vehicle.class, new JavaBeanSerializer(Vehicle.class,
					new String[] { "id", "current", "next" }));
			JSONSerializer serializer = new JSONSerializer(mapping);
			serializer.write(vs);
			String jsonString = serializer.toString();
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	public String calculateRoadStatus()  {
		HttpServletRequest req = ServletActionContext.getRequest();
		int area = Integer.parseInt(req.getParameter("area"));
		List<RoadStatus> rs=roadService.calculateRoadStatus(area) ;       //计算道路状态
		RoadStatus rs1=new RoadStatus();
		rs.add(rs1);
		SerializeConfig mapping = new SerializeConfig();
		mapping.put(RoadStatus.class, new JavaBeanSerializer(RoadStatus.class,
				new String[] { "start", "end", "level" }));
		JSONSerializer serializer = new JSONSerializer(mapping);
		serializer.write(rs);
		String jsonString = serializer.toString();
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public String uploadMap() {
		try {
			HttpServletRequest req = ServletActionContext.getRequest();
			String ls = req.getParameter("tiles");
			JSONArray jarray = JSON.parseArray(ls);
			List<Tile> ts = new ArrayList<Tile>();
			for (Object o : jarray)
				ts.add(JSON.toJavaObject((JSONObject) o, Tile.class));
			roadService.saveOrUpdateTiles(ts);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	public String getMap(){
		try {
			List<Tile> tiles=roadService.getAllTiles();
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().write(tiles.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public RoadService getRoadService() {
		return roadService;
	}

	public void setRoadService(RoadService roadService) {
		this.roadService = roadService;
	}

	public PointService getPointService() {
		return pointService;
	}

	public void setPointService(PointService pointService) {
		this.pointService = pointService;
	}
}
